//
//  RealNameViewController.m
//  MyNewProject
//
//  Created by 孙 on 2019/1/30.
//  Copyright © 2019 sun. All rights reserved.
//

#import "RealNameViewController.h"

@interface RealNameViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property(nonatomic,strong)UITableView * myTalbleView;
@property(nonatomic,copy)NSString * firstStr;

@property(nonatomic,copy)NSString * secondStr;

@property (nonatomic, strong) UITextField *textField;
@end

@implementation RealNameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (self.myVC == REALNAME) {
        self.gk_navTitle = @"实名认证";
        if (!IsStrEmpty([UserInfoSingleton shareInstance].userInfo.name)) {
            self.firstStr = [UserInfoSingleton shareInstance].userInfo.name;
        }
        if (!IsStrEmpty([UserInfoSingleton shareInstance].userInfo.card)) {
            self.secondStr = [UserInfoSingleton shareInstance].userInfo.card;
            
        }
    }
    else
    {
        self.gk_navTitle = @"支付宝绑定";

    }
    [self.view addSubview:self.myTalbleView];
  
    
  
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    //过滤非汉字字符
    textField.text = [self filterCharactor:textField.text withRegex:@"[^\u4e00-\u9fa5]"];
    
    if (textField.text.length >= 4) {
        textField.text = [textField.text substringToIndex:4];
    }
    return NO;
}

- (void)textFiledEditChanged:(id)notification{
    
    UITextRange *selectedRange = self.textField.markedTextRange;
    UITextPosition *position = [self.textField positionFromPosition:selectedRange.start offset:0];
    
    if (!position) { // 没有高亮选择的字
        //过滤非汉字字符
        self.textField.text = [self filterCharactor:self.textField.text withRegex:@"[^\u4e00-\u9fa5]"];
        
    }else { //有高亮文字
        //do nothing
    }
}

//根据正则，过滤特殊字符
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
    NSString *searchText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
    return result;
}

-(UITableView*)myTalbleView
{

    if (_myTalbleView ==nil) {
        _myTalbleView =[[UITableView alloc] initWithFrame:CGRectMake(0,SKTopBar_Height ,SCREEN_WIDTH , SCREENH_HEIGHT-SKTopBar_Height) style:UITableViewStyleGrouped];
        _myTalbleView.dataSource = self;
        _myTalbleView.delegate = self;
        _myTalbleView.estimatedRowHeight = 0;
        _myTalbleView.estimatedSectionFooterHeight = 0;
        _myTalbleView.estimatedSectionHeaderHeight = 0;
        _myTalbleView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTalbleView.bounces = NO;

        if (@available(iOS 11.0, *)) {

            _myTalbleView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

        } else {

            self.automaticallyAdjustsScrollViewInsets = NO;

        }
        
        UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardDismiss:)];
        [_myTalbleView addGestureRecognizer:tapGesture];
        
    }
    return _myTalbleView;
}
-(void)keyboardDismiss:(UIGestureRecognizer*)tap
{
    [self.view endEditing:YES];
}
#pragma mark -  UITableView 代理相关

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 2;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{


    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (!cell) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
    }

    for (id view in [cell.contentView subviews])
    {

        [view removeFromSuperview];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    NSString * labText = @"";
    if (self.myVC == REALNAME) {
        labText = @"身份证号";
    }
    else
    {
        
        labText = @"姓名";

    }
    

    UILabel * label = [[UILabel alloc] init];
    label.textColor = SKColorWithHex(0x444444);
    label.font = SKFONT_Medium(15);
    label.textAlignment = NSTextAlignmentLeft;
    [cell.contentView addSubview:label];
    CGFloat labWidth = [NSString getWidthWithString:labText font:label.font lineBreakModel:NSLineBreakByCharWrapping];
    label.frame = CGRectMake(25, 0, labWidth, 50);

    
    if (indexPath.row <1) {
        UIImageView * imageView =[[UIImageView alloc] initWithFrame:CGRectMake(0, label.bottom -0.5, SCREEN_WIDTH, 0.5)];
        imageView.backgroundColor =SKRGBColor(237, 237, 237);
        [cell.contentView addSubview:imageView];
    }
    
    
    UITextField * textField =[[UITextField alloc] initWithFrame:CGRectMake(labWidth+25 +10, 0, SCREEN_WIDTH-50, 50)];
    textField.font = SKFONT_Medium(15.0);
    textField.textColor = SKColorWithHex(0x444444);
//    textField.delegate = self;
    textField.tag = 100000000000 + indexPath.row;
//    textField.bk_shouldChangeCharactersInRangeWithReplacementStringBlock = ^BOOL(UITextField * textField, NSRange range, NSString * str) {
//
//
//        NSLog(@"----%@---",textField.text);
//
////        if (indexPath.row==0) {
////
////            if (str.length == 0) {
////
////
////                return YES;
////            }
////            if ([self isChinese:str]) {
////
////                return YES;
////            }
////            return NO;
////        }
////        else
////        {
////            self.secondStr = textField.text;
////
////        }
//
//        return YES;
//    };
    if (indexPath.row==0) {

        if (!IsStrEmpty(self.firstStr)) {
            textField.text= self.firstStr ;

        }
    }
    else
    {
        if (!IsStrEmpty(self.secondStr)) {
            textField.text= self.secondStr ;

        }
    }
    if (self.myVC == REALNAME) {
        if (indexPath.row==0) {

            label.text = @"姓   名";
            textField.placeholder = @"请输入您的真实姓名";

            if (self.textField==nil) {
                self.textField = textField;
                [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:self.textField];
            }
           
            
        }
        else
        {
            label.text = @"身份证号";

            textField.placeholder = @"请输入您的身份证号";
          
        }
    }
    else
    {
        if (indexPath.row==0) {
            label.text = @"姓名";

            textField.placeholder = @"请输入您的真实姓名";

        }
        else
        {
            label.text = @"账号";

            textField.placeholder = @"请输入您的支付宝账号";

        }
    }

    [cell.contentView addSubview:textField];


    return cell;



}
- (BOOL)isChinese:(NSString*)str{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:str];

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat  heightForRow = 50;

    return heightForRow;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
  
    UIView  * bgView = [UIView new];

    bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 200);

    
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(25,0,SCREEN_WIDTH-50 ,30);
    label.numberOfLines = 0;
    label.font = SKFONT_Medium(13);
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = SKColorWithHex(0x999999);
    [bgView addSubview:label];
    
    NSString * labText = @"";
    if (self.myVC == REALNAME) {
        labText = @"请再三确认您的姓名、身份证号码是否正确。";
    }
    else
    {
        
        labText = @"请再三确认您的支付宝姓名、账号是否正确。";
        
    }
    
   
    label.text = labText;
    
    UIFont * font = [UIFont systemFontOfSize:18];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.frame = CGRectMake(20, bgView.height -44 , SCREEN_WIDTH -20 *2 , 44);

    button.imageView.contentMode = UIViewContentModeScaleAspectFit;

    button.backgroundColor = SKColorWithHex(0x7ab801);

//    button.layer.cornerRadius = button.height/2;
//
//    button.layer.masksToBounds = YES;

    [button setTitle:@"保存" forState:UIControlStateNormal];

    button.titleLabel.font = font ;

    [button setTitleColor:SKColorWithHex(0xFFFFFF) forState:UIControlStateNormal];

    [button addTarget:self action:@selector(confirmDeal:) forControlEvents:UIControlEventTouchUpInside];


    [bgView addSubview:button];

 

    return bgView;

}
#pragma mark -- 保存
-(void)confirmDeal:(UIButton *)sender
{
    
    [self.view endEditing:YES];
    
    UITableViewCell * firstCell  = [self.myTalbleView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    UITextField * firstTextField = [firstCell.contentView viewWithTag:100000000000];



    UITableViewCell * secondCell  = [self.myTalbleView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    UITextField * secondTextField = [secondCell.contentView viewWithTag:100000000001];

    NSString * url = @"";
    NSDictionary * dic = nil;
    
    if (self.myVC == REALNAME) {
        if (IsStrEmpty(firstTextField.text)) {
            
            [self.view makeToast:@"姓名不能为空" duration:1 position:CSToastPositionCenter];
            
            return;
        }
        
//        if ([self isChinese:firstTextField.text]) {
//
//            [self.view makeToast:@"姓名只能为纯汉字" duration:1 position:CSToastPositionCenter];
//
//            return;
//        }
        if (IsStrEmpty(secondTextField.text)) {
            
            [self.view makeToast:@"身份证号不能为空" duration:1 position:CSToastPositionCenter];
            return;
        }
        
        
        url = @"my/setCard";
        dic = @{@"uid":self.uid,@"loginKey":self.loginKey,@"name":SafeString(firstTextField.text),@"card":SafeString(secondTextField.text)};
    }
    else
    {
        
    }

    
   
    SKWeakSelf;
    
    [YQNetworking postWithUrl:url params:dic reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        
        if (self.myVC == REALNAME) {
            
            if ([response[@"status"] isEqualToString:@"ok"]) {
                
                if (SKUserUserDefaults_Get(@"UserInfo"))
                {
                    NSLog(@"%@",SKUserUserDefaults_Get(@"UserInfo"));
                    
                    NSDictionary * dic = SKUserUserDefaults_Get(@"UserInfo");

                    NSMutableDictionary * newDic =[NSMutableDictionary dictionaryWithDictionary:dic];
                    if (!IsStrEmpty(response[@"data"][@"card"])) {
                        newDic[@"card"] = response[@"data"][@"card"];

                    }
                    if (!IsStrEmpty(response[@"data"][@"name"])) {
                        newDic[@"name"] = response[@"data"][@"name"];
                        
                    }
                    SKUserUserDefaults_Save(newDic, @"UserInfo");
                    
                    [UserInfoSingleton shareInstance].userInfo = [YPLoginUserInfo modelObjectWithDictionary:SKUserUserDefaults_Get(@"UserInfo")];
                }
                [self.view makeToast:@"修改成功" duration:1 position:CSToastPositionCenter];

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
            }
            else
            {
                 [self.view makeToast:SafeString(response[@"msg"]) duration:1 position:CSToastPositionCenter];
            }
           
        }
        else
        {
            
        }
        
        
        
    } failBlock:^(NSError *error) {
        [self.view makeToast:@"绑定失败" duration:1 position:CSToastPositionCenter];
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//    if (section == 0) {
        return 10;
//    }
//    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 200;

//    if (section == 1) {
//        return 200;
//    }
//    return CGFLOAT_MIN;

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            
        }
            break;
        case 1:
        {

        }
            break;
        case 2:
        {

        }
            break;

        default:
            break;
    }

}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
